# Copyright (c) 2010 Phillip Nguyen.
# All rights reserved.

"""
This module replaces pyglet.resource which has problems with its
method for searching for files.  The primary purpose of this module
to provide a default resource handler that will cache loaded textures.

The module exposes a texture(name, anchor_x, anchor_y) method which
uses the default handler to load (and cache) the asked for texture.

name is a filename relative to the search path and anchor_x and anchor_y
are parameters giving the offset of the sprite texture from its parent's
body (Note that the anchor point can only be defined once, during the first
time the texture is loaded.)
"""

__docformat__ = 'plaintext'

import sys, os, weakref
import pyglet

class ResourceNotFoundException (Exception):
    def __init__(self, name, paths):
        Exception.__init__(self, 'Resource "%s" could not be found in %s' % (name, paths))

class ResourceHandler:
    """This is class to manage game resources.  It is used to load textures
    and will cache loaded textures so that subsequent requests for the same
    texture return the one already loaded, rather than creating a new
    texture from file."""
    def __init__(self, paths=None):
        """By default the resource search path is set to the directory containing
        the script used to invoke python.  You may optionally pass in a list of
        additional search paths."""
        #modulepath = os.path.dirname(os.path.realpath( __file__ ))
        modulepath = os.path.realpath( sys.path[0] )
        self.paths = [modulepath]
        self.paths.extend(paths or [])
        #print "resource paths = %s" % self.paths
        self.cached_textures = weakref.WeakValueDictionary()
        
    def get_path(self, name):
        """Try to find the named file somewhere on the search path."""
        for base in self.paths:
            path = os.path.join(base, name)
            if os.path.isfile(path):
                return path
        raise ResourceNotFoundException(name, self.paths)
    
    def texture(self, name, anchor_x=0, anchor_y=0):
        """Return a texture created from the named file."""
        if name in self.cached_textures:
            return self.cached_textures[name]

        path = self.get_path(name)
        texture = pyglet.image.load(path).get_texture()
        texture.anchor_x = anchor_x
        texture.anchor_y = anchor_y
        self.cached_textures[name] = texture
        return texture

# Only need one resource handler, so we create it here
# and then make an alias to its texture loading method.
_default_handler = ResourceHandler()
texture = _default_handler.texture
